import axios, {AxiosRequestConfig} from 'axios'
import {ElMessage} from 'element-plus'
import router from '@/router'

// 创建axios实例
const request = axios.create({
    baseURL: import.meta.env.VITE_BACKEND_BASE_URL,
    timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(
    (config: AxiosRequestConfig|any) => {
        // 如果有token，在请求头携带token
        const token = localStorage.getItem('token')
        if (token) {
            config.headers = {
                ...config.headers,
                'Authorization': `Bearer ${token}`
            }
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
    (response) => {
        return response.data
    },
    (error) => {
        // 处理错误响应
        let message = ''
        const status = error.response?.status
        switch (status) {
            case 401:
                message = error.response?.data?.message || '登录过期，请重新登录'

                // 清除本地token
                localStorage.removeItem('token')
                // 跳转到登录页
                router.replace('/login')
                break
            case 403:
                message = '无权访问'
                break
            case 404:
                message = '请求地址错误'
                break
            case 500:
                message = '服务器出现问题'
                break
            default:
                message = '网络出现问题'
                break
        }
        ElMessage.error(message)
        return Promise.reject(error)
    }
)

export default request
